﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using RayDen.Library.Core.Primitives;

namespace RayDen.Library.Data.Utility
{
    public static unsafe class MemoryHelper
    {
        public static byte[] UnsafeFill(byte value, byte[] a)
        {
            Int64 fillValue = BitConverter.ToInt64(new[] { value, value, value, value, value, value, value, value }, 0);

            Int64* src = &fillValue;
            fixed (byte* ptr = &a[0])
            {
                var dest = (Int64*)ptr;
                int length = a.Length;
                while (length >= 8)
                {
                    *dest = *src;
                    dest++;
                    length -= 8;
                }
                var bDest = (byte*)dest;
                for (byte i = 0; i < length; i++)
                {
                    *bDest = value;
                    bDest++;
                }
            }
            return a;
        }


        public static void MemCopy(float[] data, float* arr)
        {
            Marshal.Copy(data, 0, new IntPtr(arr), data.Length);
        }

        public static void MemCopy(RgbSpectrum[] srcData, RgbSpectrum* destArr)
        {
            int i = 0;
            foreach (var rgbSpectrum in srcData)
            {
                destArr[i++] = rgbSpectrum;
            }
            /*
            GCHandle handle = GCHandle.Alloc(srcData, GCHandleType.Pinned);
            try
            {
                IntPtr arrayPointer = handle.AddrOfPinnedObject();
                Marshal.Copy(arrayPointer, new[]{new IntPtr(destArr)}, 0, srcData.Length-1);

            }
            finally
            {
                if (handle.IsAllocated)
                {
                    handle.Free();
                }
            }*/
        }

        [DllImport("kernel32.dll", EntryPoint = "RtlCopyMemory")]
        public static extern void CopyMemory(IntPtr Destination, IntPtr Source, uint Length);
    }
}
